﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace BYS.XiAnComDept.BussLogic
{
    public class ProjectFieldBll : BllBase
    {
        public ProjectFieldBll(ComDeptContext db) : base(db) { }

        public List<ProjectField> GetProjectFieldNamesForFundType(DateTime year, string fundTypeName)
        {
            IQueryable<ICollection<ProjectField>> projectFields = this.Db.Funds
                    .Where(x => x.FundType.FundTypeName == fundTypeName && x.Year.Year == year.Year)
                    .Select(x => x.ProjectFields);

            List<ProjectField> projectFieldList = new List<ProjectField>();

            foreach (ICollection<ProjectField> projectFieldItems in projectFields)
            {
                foreach (ProjectField projectField in projectFieldItems)
                {
                    if (!projectFieldList.Select(x=>x.FieldName).Contains(projectField.FieldName.Trim()))
                    {
                        projectFieldList.Add(projectField);
                    }
                }
            }
            return projectFieldList.OrderBy(x => x.OrderNo).ToList();
        }

        public List<string> GetProjectFieldNames(IEnumerable<Fund> funds)
        {
            List<string> projectFieldNames = new List<string>();

            foreach (Fund fund in funds)
            {
                ICollection<ProjectField> projectFieldItems = fund.ProjectFields;
                foreach (ProjectField projectField in projectFieldItems)
                {
                    if (!projectFieldNames.Contains(projectField.FieldName.Trim()))
                    {
                        projectFieldNames.Add(projectField.FieldName.Trim());
                    }
                }
            }
            return projectFieldNames;
        }

        public bool IsHavingSaveProjectFieldNames(IEnumerable<Fund> funds)
        {
            if (funds.Count() <= 1)
            {
                return true;
            }
            IEnumerable<string> projectFieldNames = funds.First().ProjectFields.Select(x => x.FieldName);
            foreach (Fund fund in funds)
            {
                IEnumerable<string> currentProjectFieldNames = fund.ProjectFields.Select(x => x.FieldName);
                if (!currentProjectFieldNames.IsSameCollection(projectFieldNames))
                {
                    return false;
                }
            }
            return true;
        }
    }
}
